import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class SealImageGenerator {

    public static void main(String[] args) {
        String text = "王智峰";
        int padding = 10;  // 方框与文字之间的填充
        int borderThickness = 5;  // 方框的厚度
        String outputImagePath = "C:\\Users\\tlcb\\Pictures\\Camera Roll\\mingimage40.png";

        // 创建一个临时的BufferedImage对象来计算文字的尺寸
        BufferedImage tempImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = tempImage.createGraphics();

        // 设置字体
        Font font = new Font("宋体", Font.BOLD, 40);
        g2d.setFont(font);
        FontMetrics fontMetrics = g2d.getFontMetrics();

        // 计算文字的宽度和高度
        int stringWidth = fontMetrics.stringWidth(text);
        int stringHeight = fontMetrics.getAscent();

        // 计算图片的宽度和高度
        int width = stringWidth + padding * 2 + borderThickness * 2;
        int height = stringHeight + padding * 2 + borderThickness * 2;

        // 创建最终的BufferedImage对象
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        g2d = bufferedImage.createGraphics();

        // 设置背景为透明
        g2d.setColor(new Color(255, 255, 255, 0));
        g2d.fillRect(0, 0, width, height);

        // 画红色的方框
        g2d.setColor(Color.RED);
        g2d.fillRect(0, 0, width, borderThickness); // 上边框
        g2d.fillRect(0, height - borderThickness, width, borderThickness); // 下边框
        g2d.fillRect(0, 0, borderThickness, height); // 左边框
        g2d.fillRect(width - borderThickness, 0, borderThickness, height); // 右边框

        // 设置字体
        g2d.setFont(font);

        // 在方框中心绘制文字
        g2d.setColor(Color.RED);
        int x = borderThickness + padding;
        int y = borderThickness + padding + fontMetrics.getAscent();
        g2d.drawString(text, x, y);

        // 释放Graphics2D对象
        g2d.dispose();
        // 将图片转换为byte[]
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 保存图片到文件
        try {
            ImageIO.write(bufferedImage, "png", baos);
            ImageIO.write(bufferedImage, "png", new File(outputImagePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] imageBytes = baos.toByteArray();
        System.out.println("Generated image byte array length: " + imageBytes.length);
        // 关闭资源
        try {
            baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
